package com.rookie.rabbit.modular.util;

import com.rabbitmq.client.BuiltinExchangeType;
import org.springframework.util.StringUtils;

public class RabbitUtils {

    public static int isTrueDefault(Integer value) {
        if (value == null) {
            return 1;
        } else {
            return value;
        }
    }

    public static int isFalseDefault(Integer value) {
        if (value == null) {
            return 0;
        } else {
            return value;
        }
    }

    public static String getDefaultRoutingKey(Enum<?> e, String value) {
        if (!StringUtils.hasText(value)) {
            String s = e.name().toLowerCase();
            s = s.replaceAll("_", ".");
            s += ".key";
            return s;
        } else {
            return value;
        }
    }

    public static BuiltinExchangeType getDefaultExchange(BuiltinExchangeType exchange) {
        if (exchange == null) {
            return BuiltinExchangeType.DIRECT;
        } else {
            return exchange;
        }
    }

    public static String getDefaultExchangeName(Enum<?> e, String value) {
        if (!StringUtils.hasText(value)) {
            return e.name().toLowerCase();
        } else {
            return value;
        }
    }

    public static String getDefaultQueueName(Enum<?> e, String value) {
        if (!StringUtils.hasText(value)) {
            String name = e.name().toLowerCase();
            return name.replaceAll("_", "-");
        } else {
            return value;
        }
    }

    /**
     * 如果值为空则按照规则转换枚举名称
     *
     * @param e     枚举
     * @param value 值
     * @return 结果
     */
    public static String getDefaultBeanName(Enum<?> e, String value) {
        StringBuilder result = new StringBuilder();
        if (!StringUtils.hasText(value)) {
            String[] split = getEnumArrayName(e);
            if (split.length <= 1) {
                return split[0];
            }
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    result = new StringBuilder(split[i]);
                    continue;
                }
                String s = split[i];
                if (!StringUtils.hasText(s)) {
                    continue;
                }
                split[i] = captureName(split[i]);
                result.append(split[i]);
            }
        } else {
            return value;
        }
        return result.toString();
    }

    /**
     * 首字母转大写
     *
     * @param str 字符
     * @return 结果
     */
    private static String captureName(String str) {
        char[] cs = str.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }

    private static String[] getEnumArrayName(Enum<?> e) {
        String name = e.name();
        name = name.toLowerCase();
        return name.split("_");
    }
}
